package com.moyv.schoolbbs.service;


import android.os.Handler;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static com.moyv.schoolbbs.config.AccountConstant.TOKEN;
import static com.moyv.schoolbbs.config.URLConstant.DELETE_URL;
import static com.moyv.schoolbbs.util.HttpUtil.createClient;

public class DeletePostService {
    public static void deletePost(int postId, Handler handler) {
        String url = DELETE_URL;
        OkHttpClient okHttpClient = createClient();
        FormBody formBody = new FormBody.Builder()
                .add("postId", String.valueOf(postId))
                .add("token", TOKEN)
                .build();
//        发送请求操作
        Request request = new Request.Builder()
                .post(formBody)
                .url(url)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                handler.sendMessage(handler.obtainMessage(505));
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String responseData = response.body().string();
                System.out.println(responseData);
                JSONObject object = null;
                int result = 0;
                try {
                    object = new JSONObject(responseData);
                    result = object.getInt("result");
                    System.out.println(object);
                    if (result == 1) {
                        handler.sendMessage(handler.obtainMessage(200));
                    } else {
                        handler.sendMessage(handler.obtainMessage(505));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    handler.sendMessage(handler.obtainMessage(505));
                }

            }
        });
    }
}
